<template>
    <div>
        <div class="title">
            <span>建行活动</span>
            <span :key="key"></span>
            <div>
                <el-button type="primary" @click="addCouponFn">新增活动</el-button>
                <el-button
                icon="el-icon-refresh"
                @click.native="updateClick()"
                ></el-button>
            </div>
        </div>
        <div class="container">
            <!-- 搜索板块 -->
            <div class="screeningBox">
                <el-form ref="searchObj" :model="searchObj" v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8">
                    <div class="leftBox">
             
                        <div class="leftitem">
                            <el-form-item class="ipt" prop="merchantNo">
                                <el-input placeholder="商户号"  v-model="searchObj.merchantNo"></el-input>
                            </el-form-item>
                        </div>
                        <div class="leftitem">
                            <el-form-item class="ipt" prop="merchantName">
                                <el-input placeholder="商户名" v-model="searchObj.merchantName"></el-input>
                            </el-form-item>
                        </div>
                    </div>
                    <div class="rightBox">
                        <div class="leftitem">
                            <el-form-item class="ipt timebox" prop="activityName">
                                <el-date-picker
                                v-model="date"
                                type="datetimerange"
                                :picker-options="pickerOptions"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                :clearable="false"
                                :default-time="['00:00:00', '23:59:59']"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </div>
                        <div class="leftitem">
                            <el-form-item style="width:33%" prop="time">
                                <el-input placeholder="活动名称" v-model="searchObj.activityName"></el-input>
                            </el-form-item>
                            <el-form-item style="margin-left: 10px">
                                <el-button icon="el-icon-search" type="primary" @click="soso" :disabled="isDisable">
                                    搜索
                                </el-button>
                                <el-button icon="el-icon-refresh" type="primary" @click="reset">重置</el-button>
                            </el-form-item>
                        </div>
                    </div>
                </el-form>
                <el-form ref="searchObj" :model="searchObj" v-else>
                    <div class="rightBox">
                        <div class="leftitem">
                            <el-form-item prop="time">
                                <el-date-picker
                                v-model="date"
                                type="datetimerange"
                                :picker-options="pickerOptions"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                :clearable="false"
                                :default-time="['00:00:00', '23:59:59']"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </div>
                        <div class="leftitem">
                            <el-form-item style="width:33%" prop="activityName">
                                <el-input placeholder="活动名称" v-model="searchObj.activityName"></el-input>
                            </el-form-item>
                            <el-form-item style="margin-left: 10px">
                                <el-button icon="el-icon-search" type="primary" @click="soso" :disabled="isDisable">
                                    搜索
                                </el-button>
                                <el-button icon="el-icon-refresh" type="primary" @click="reset">重置</el-button>
                            </el-form-item>
                        </div>
                    </div>
                </el-form>
            </div>
            <!-- 表格板块 -->
            <div class="tableBox">
                <el-table
                    ref="multipleTable"
                    :data="couponData"
                    tooltip-effect="dark"
                    style="width: 100%"
                    @selection-change="handleSelectionChange"
                    stripe
                    v-loading="loading"
                    :header-cell-style="tableHeaderColor">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column
                    prop="id"
                    align="center"
                    label="序号"
                    width="60"
                ></el-table-column>
                <el-table-column
                  prop="activityName"
                  label="活动名称"
                  align="center"
                ></el-table-column>
                <el-table-column
                    prop="merchantNo"
                    label="商户号"
                    align="center"
                ></el-table-column>
                <el-table-column
                    prop="merchantName"
                    label="商户名"
                    align="center"
                ></el-table-column>
                <el-table-column
                    prop="createTime"
                    label="创建时间"
                    align="center"
                ></el-table-column>
                <el-table-column
                    fixed="right"
                    align="center"
                    label="操作"
                    width="240"
                >
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            size="small"
                            @click="couponDetail(scope.row)">
                            详情
                        </el-button>
                        <el-button
                            type="text"
                            size="small"
                            @click="addCouponFn(scope.row)">
                            修改
                        </el-button>
                        <el-button
                            type="text"
                            size="small"
                            @click="deletCoupon(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
            <el-pagination
                background
                @current-change="handleCurrentChange"
                @size-change="sizechange"
                :page-sizes="[10,20,30,40,50]"
                :page-size='cur_size'
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            ></el-pagination>
            </div>
            </div>
            <!-- 新增/修改活动 -->
            <el-dialog
                :title="getTitle"
                center
                :visible.sync="couponVisible"
                @closed="couPondialogBtn"
                width="45%"
                :close-on-click-modal="false">
                <el-form label-position="left"  label-width="120px" :rules="couponRules" ref="addCouponForm" :model="addCouponForm">
                    <el-form-item class="addipt" prop="merchantName" label="商户名" v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8">
                        <el-autocomplete
                            style="width: 100%"
                            v-model.trim="addCouponForm.merchantName"
                            :fetch-suggestions="merchantslist"
                            :trigger-on-focus="false"
                            :debounce="300"
                            placeholder="商户名"
                            @select="okmerchants">
                        </el-autocomplete>
                    </el-form-item>
                    <el-form-item class="addipt" prop="activityName" label="活动名称">
                        <el-input placeholder="活动名称" v-model.trim="addCouponForm.activityName"></el-input>
                    </el-form-item>
                    <el-form-item class="ipt" prop="type" label="分摊类型">
                        <el-select style="width: 100%;" v-model="addCouponForm.type" placeholder="分摊类型">
                            <el-option label="按比例分摊" :value="'1'"></el-option>
                            <el-option label="按金额分摊" :value="'2'"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item class="addipt ratioIpt" prop="ratio" label="商户分摊比例" v-if="addCouponForm.type == '1'">
                        <el-input placeholder="商户分摊比例" v-model.trim="addCouponForm.ratio"></el-input>
                        <el-tooltip class="item" effect="dark" content="商户优惠金额=总优惠金额×分摊比例%" placement="bottom">
                          <i class="el-icon-question"></i>
                        </el-tooltip>
                        <span class="ratio-tips">分摊比例取值范围（%）：0.01~100，可精确到2位小数</span>
                    </el-form-item>
                    <el-form-item class="addipt" prop="merchantAmount" label="商户分摊金额" v-if="addCouponForm.type == '2'">
                        <el-input placeholder="商户分摊金额" v-model.trim="addCouponForm.merchantAmount"></el-input>
                        <i class="el-icon-question"></i>
                        <span class="ratio-tips">单位（元），可精确到2位小数</span>
                    </el-form-item>
                    <el-form-item style="text-align:right">
                        <el-button type="primary" @click="onSubmit">确定</el-button>
                        <el-button @click="couPondialogBtn">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import { merchantlist, addCoupon, updateCoupon, delCoupon, getCoupon } from '@/api/api'
import { getTimeFn } from '@/utils/getday.js'
export default {
    name: 'ccbcoupon',

    data() {
        var checkAmt = (rule, value, cb) => {
          // 分摊金额的正则表达式
          const regAmt = /^(0\.0*[1-9]\d*|0\.[1-9]\d*|[1-9]\d*(\.\d{1,2})?|[1-9])$/
          if (regAmt.test(value)) {
            //合法的分摊比例
            return cb()
          }
          cb(new Error('请填写正确的分摊金额'))
        }
        var checkRatio = (rule, value, cb) => {
            // 分摊比例的正则表达式
            const regRatio = /^(0\.(0[1-9]|[1-9]\d{0,1})|[1-9]\d{0,1}(\.\d{1,2})?|100(\.0{1,2})?)$/
            if (regRatio.test(value)) {
                //合法的分摊比例
                return cb()
            }
            cb(new Error('请填写正确的分摊比例'))
        }
        return {
            pickerOptions: {
                // 设置不能超过未来时间
                // disabledDate: (time) => {
                //   // 设置可选择的日期为今天之后的一个月内
                //   const curDate = (new Date()).getTime()
                //   // 这里算出一个月的毫秒数,这里使用30的平均值,实际中应根据具体的每个月有多少天计算
                //   const day = 31 * 24 * 3600 * 1000
                //   const dateRegion = curDate - day
                //   return time.getTime() > Date.now() - 8.64e7 ||
                //   time.getTime() < dateRegion
                // }
                // 设置不能超过当天的23:59:59
                disabledDate(time) {
                let nowDate = new Date();
                let date = {
                    year: nowDate.getFullYear(),
                    month: nowDate.getMonth() + 1,
                    date: nowDate.getDate(),
                };
                let timeDate =
                    date.year + "-" + date.month + "-" + date.date + " 23:59:59";
                let times = new Date(timeDate).getTime();
                return time.getTime() > times;
                },
            },
            couponRules: {
                merchantName: [
                    { required: true, message: '请选择商户', trigger: 'blur' }
                ],
                activityName: [
                    { required: true, message: '请填写活动名称', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择分摊类型', trigger: 'blur' }
                ],
                merchantAmount: [
                    { required: true, message: '请填写分摊金额', trigger: 'blur' },
                    { validator: checkAmt, trigger: 'blur' }
                ],
                ratio: [
                    { required: true, message: '请填写分摊比例', trigger: 'blur' },
                    { validator: checkRatio, trigger: 'blur' }
                ]
            },
            total: 0,
            cur_page: 1,
            cur_size: 10,
            key: 0,
            date: "",
            userinfo: {},
            searchObj: {
                merchantNo: '',
                merchantName: '',
                activityName: '',
            },
            conditions: {
                BDname: "",
                bdId: "",
                merchantId: "",
            },
            addCouponForm: {
                merchantId: '',
            },
            loading: false,
            isDisable: false,
            couponVisible: false,
            couponData: [],
            getTitle: '',
            isUpdate: false,
        };
    },

    created() {
        this.userinfo = JSON.parse(sessionStorage.getItem("userInfo"));
        if(this.userinfo.username != 'admin') {
            this.addCouponForm.merchantId = this.userinfo.mid
        }
        const start = new Date().getTime() - ((24 * 60 * 60 * 1000) * 30)
        const finish = new Date().getTime()
        let starttime = getTimeFn(start)
        let finishtime = getTimeFn(finish)
        const date1 = starttime + " 00:00:00";
        const date2 = finishtime + " 23:59:59";
        this.date = [date1, date2];
        this.getCouponFn()
    },

    methods: {
        //修改thead 背景色
        tableHeaderColor({ row, column, rowIndex, columnIndex }) {
            if (rowIndex === 0) {
                return "background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;";
            }
        },
        // 分页导航
        handleCurrentChange(val) {
            this.cur_page = val;
            this.getCouponFn();
            this.$nextTick(() => {
                document.querySelectorAll(".content")[0].scrollTop = "0";
            });
        },
        // 分页数量
        sizechange(val) {
            this.cur_size = val;
            this.getCouponFn();
            this.$nextTick(() => {
                document.querySelectorAll(".content")[0].scrollTop = "0";
            });
        },
        // 刷新
        updateClick() {
            this.loading = true;
            this.getCouponFn();
        },
        // 搜索
        soso() {
          if(this.date == null || this.date.length == 0 || this.date == undefined) {
            this.$message.error('查询时间不能为空')
            return
          }
            this.getCouponFn()
        },
        // 重置
        reset() {
            this.$refs.searchObj.resetFields()
            const start = new Date().getTime() - ((24 * 60 * 60 * 1000) * 30)
            const finish = new Date().getTime()
            let starttime = getTimeFn(start)
            let finishtime = getTimeFn(finish)
            const date1 = starttime + " 00:00:00";
            const date2 = finishtime + " 23:59:59";
            this.date = [date1, date2];
        },
        //多选框
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 获取商户列表初始化
        merchantslist(queryString, cb) {
        let sosolist = {};
        sosolist = {
            page: 1,
            size: 20,
            merchantName: this.addCouponForm.merchantName,
        };
        merchantlist(sosolist).then((res) => {
            // console.log(res);
            if (res.code == 405) {
                sessionStorage.removeItem("token");
                this.$router.push("/login");
            } else {
            this.merchantarrlist = [];
            for (var i = 0; i < res.data.length; i++) {
                this.merchantarrlist.push({
                value: res.data[i].merchantName,
                merchantId: res.data[i].id,
                });
            }
            let results = queryString
                ? this.merchantarrlist.filter(this.createFilter(queryString))
                : this.merchantarrlist;
            // 调用 callback 返回建议列表的数据
            cb(results);
            }
        });
        },
        createFilter(queryString) {
            return (restaurant) => {
                return (
                    restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
                );
            };
        },
        // 选择商户
        okmerchants(val) {
            console.log(val);
            // this.addCouponForm.merchantId = val.mid;
            this.addCouponForm.merchantId = val.merchantId;
        },
        // 获取分摊信息
        async getCouponFn() {
            this.loading = true
            let list = {}
            if(this.userinfo.rolesId == 1 || this.userinfo.rolesId == 8 ) {
              list = {
                merchantNo: this.searchObj.merchantNo,
                merchantName: this.searchObj.merchantName,
                activityName: this.searchObj.activityName,
                startTime: this.date[0],
                finishTime: this.date[1],
                page: this.cur_page,
                size: this.cur_size,
              }    
              let res = await getCoupon(list)
                if (res.code == 405) {
                    sessionStorage.removeItem("token");
                    this.$router.push("/login");
                } else {
                    if(res.code == 200) {
                        this.couponData = res.data
                        this.loading = false
                        this.couponData.forEach((item) => {
                            item.ratio = item.ratio / 100;
                            item.merchantAmount = item.merchantAmount ? item.merchantAmount / 100 : 0;
                        })
                        this.total = res.pageInfo.recordCount
                    } else {
                        this.loading = false
                    }
                }
            } else {
              list = {
                merchantId: this.userinfo.mid,
                // merchantName: this.searchObj.merchantName,
                activityName: this.searchObj.activityName,
                startTime: this.date[0],
                finishTime: this.date[1],
                page: this.cur_page,
                size: this.cur_size,
              }    
              let res = await getCoupon(list)
                if (res.code == 405) {
                    sessionStorage.removeItem("token");
                    this.$router.push("/login");
                } else {
                    if(res.code == 200) {
                        this.couponData = res.data
                        this.loading = false
                        this.couponData.forEach((item) => {
                            item.ratio = item.ratio / 100;
                            item.merchantAmount = item.merchantAmount ? item.merchantAmount / 100 : 0;
                        })
                        this.total = res.pageInfo.recordCount
                    } else {
                        this.loading = false
                    }
                }
            }
        },
        // 新增活动关闭清空内容
        couPondialogBtn() {
            this.couponVisible = false
            this.$refs.addCouponForm && this.$refs.addCouponForm.resetFields()
            this.addCouponForm = {
                merchantId: ''
            }
        },
        // 打开新增活动页面
        addCouponFn(val) {
            this.couponVisible = true
            if (val.id == undefined) {
                this.getTitle = '新增活动'
                this.isUpdate = false
            } else {
                this.isUpdate = true
                this.getTitle = '修改活动'
                this.addCouponForm = {...val}
            }
        },
        // 新增/修改按钮
        onSubmit() {
            this.$refs.addCouponForm.validate(async(valid) => {
                if (valid) {
                    var date = new Date()
                    var Y = date.getFullYear() + '-'
                    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
                    var D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' '
                    var H = date.getHours() + ':'
                    var M2 = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
                    var S = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()

                    var aa = Y + M + D + H + M2 + S
                    let ratioNum = (this.addCouponForm.ratio * 100).toFixed();
                    let merAmount = (this.addCouponForm.merchantAmount * 100).toFixed()
                    if(this.isUpdate) {
                        let updatelist = {
                            id: this.addCouponForm.id,
                            merchantId: this.addCouponForm.merchantId,
                            activityName: this.addCouponForm.activityName,
                            type: this.addCouponForm.type,
                            merchantAmount: merAmount,
                            ratio: ratioNum,
                        }
                        let res = await updateCoupon(updatelist)
                        if(res.code == 405) {
                            sessionStorage.removeItem("token");
                            this.$router.push("/login");
                        } else {
                            if(res.code == 200) {
                                this.$message.success('修改成功')
                                this.couPondialogBtn()
                            } else {
                                this.$message.error(res.message)
                            }
                        }
                    } else {
                        if(this.userinfo.mid == 18446) {
                            this.addCouponForm.merchantId = 18446
                        }
                        let list = {
                            merchantId: this.addCouponForm.merchantId,
                            activityName: this.addCouponForm.activityName,
                            type: this.addCouponForm.type,
                            merchantAmount: merAmount,
                            ratio: ratioNum,
                            createTime: aa
                        }
                        let res = await addCoupon(list)
                        if(res.code == 405) {
                            sessionStorage.removeItem("token");
                            this.$router.push("/login");
                        } else {
                            if(res.code == 200) {
                                this.$message.success('新增成功')
                                this.couPondialogBtn()
                            } else {
                                this.$message.error(res.message)
                            }
                        }
                    }
                    this.getCouponFn()
                }
            })
        },
        // 查看详情
        couponDetail(val) {
            this.$router.push({
                name: "CcbCouponDetail",
                params: {
                    id: val.id
                }
            });
        },
        // 删除分摊信息
        deletCoupon(val) {
            this.$confirm('是否确定删除？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async() => {
                let res = await delCoupon(val)
                if(res.code == 405) {
                    sessionStorage.removeItem("token");
                    this.$router.push("/login");
                } else {
                    if(res.code == 200) {
                        this.$message.success('删除成功')
                        if(this.couponData.length == 1) {
                            this.cur_page = this.cur_page - 1
                        }
                    } else {
                        this.$message.error(res.message)
                    }
                }
                this.getCouponFn()
            }).catch((e) => {
                console.log(e);
            })
        },
    }
};
</script>

<style lang="less" scoped>
.title {
  background: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 30%;
  padding: 0 15px;
  box-sizing: border-box;
}
.rightBox {
    width: 70%;
}
.leftBox > .leftitem,
.rightBox > .leftitem {
  display: flex;
}

.screeningBox .el-form{
    display: flex;
    width: 100%;
}
.ipt {
    width: 70%;
    margin-right: 10px;
    margin-bottom: 15px;
}
.tableBox {
  margin-top: 20px;
}
.ratio-tips{
    font-size: 10px;
    color: gray;
}
/deep/.ratioIpt .el-form-item__label{
  padding: 0px;
  width: 120px !important;
}
.el-icon-question{
  vertical-align: middle;
  margin-right: 10px;
}
/deep/.timebox .el-button--text{
  display: none;
}
</style>